package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RefreshTokenInterceptor implements HandlerInterceptor {
    private  final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 刷新Token的拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取tonke
        String tonke = request.getHeader("authorization");

        // token不存在，说明当前用户未登录，不需要刷新直接放行
        if (tonke == null){
            return true;
        }
        //查询Redis 用户信息
        String tokenKey = "loginToken:"+tonke;
        Map<Object, Object> userMap= stringRedisTemplate.opsForHash().entries("loginToken:" + tokenKey);
        // 判断用户是否存在
        if(userMap.isEmpty()){
            //不存在，说明用户未登录，直接放行
            return true;
        }

        //存在，说明用户已经，登录保存到ThreadLocal中
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //刷新tonke有效期
        stringRedisTemplate.expire(tonke,30, TimeUnit.MINUTES);
        //放行
        return true;
    }
}
